/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.perficient.ibuzz.service;

import com.google.api.client.http.HttpTransport;
import com.perficient.ibuzz.model.MessageReceiver;
import com.perficient.ibuzz.model.Message;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Trainning
 */
public class BuzzMessageReceiver implements MessageReceiver {

    private HttpTransport transport;

    public BuzzMessageReceiver(HttpTransport transport) {
        this.transport = transport;
    }

    @Override
    public List<Message> getMessages() {
        List<Message> ret = new ArrayList<Message>();
        try {
            BuzzActivityFeed feed = BuzzActivityFeed.list(transport);
            for (BuzzActivity activity : feed.items) {
                Message message = transform(activity);
                ret.add(message);
            }
        } catch (IOException ex) {
            Logger.getLogger(BuzzMessageReceiver.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException(ex);
        }
        return ret;
    }

    @Override
    public boolean isOutOfDate(Date lastupdate) {
        try {
            BuzzActivityFeed feed = BuzzActivityFeed.list(transport);
            for (BuzzActivity activity : feed.items) {
                Message message = transform(activity);
                if (lastupdate.before(message.getPostDate())
                        || lastupdate.before(message.getUpdateDate())) {
                    return true;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(BuzzMessageReceiver.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException(ex);
        }

        return false;
    }

    private Message transform(BuzzActivity activity) {
        Message message = new Message();
        message.setText(activity.object.content);
        message.setPostDate(new Date(activity.published.value));
        message.setUpdateDate(new Date(activity.updated.value));
        message.setAuthor(activity.actor.name);
        return message;
    }

}
